package com.hehe.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

@Slf4j
@Controller
@RequestMapping(value = "")
public class uploadImageController {

    @Value("${file.upload.path}")  // 从 application.properties 获取文件夹路径
    private String SAVE_FOLDER_PATH;

    /*
     * 将接收的base64转换成图片保存
     * @param imgByte
     * base64数据
     * @param cardNum
     * 号码
     * @return 成功返回图片保存路径，失败返回false
     */
    @PostMapping("/save_img_by_str")
    @ResponseBody
    public String saveToImgByStr(@RequestParam("imgByte") String imgByte,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {

        // 获取当前日期作为文件夹名称, 像这样 20240717
        String createNewDirStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String filepath = SAVE_FOLDER_PATH + File.separator + "article-image";
        File destfile = new File(filepath);
        if (!destfile.exists()) {
            destfile.mkdirs();
        }

        // 解析 base64 编码和文件类型
        String fileType = getFileType(imgByte);
        if (fileType == null) {
            return "Unsupported file type";
        }
        imgByte = imgByte.replaceFirst("^data:image/\\w+;base64,", "");
        String fileNameNew = getFileNameNew() + "." + fileType;

        // 解码 base64 字符串并保存文件
        byte[] imageByte = Base64.getDecoder().decode(imgByte);
        File outputFile = new File(destfile, fileNameNew);

        try (InputStream in = new ByteArrayInputStream(imageByte);
             FileOutputStream fos = new FileOutputStream(outputFile)) {
            byte[] buf = new byte[1024];
            int length;
            while ((length = in.read(buf)) != -1) {
                fos.write(buf, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error saving image";
        }

        // 返回保存路径 , 拦截器 WebConfig 里面配置的是 images
        // File.separator \ 会导致转义字符 比如 \n \q ...
        // 但是 / 不会
        String lastPath = "images/article-image/" + fileNameNew;
        log.info("返回图片路径：" + lastPath);
        return lastPath;
    }


    private String getFileType(String imgByte) {
        if (imgByte.contains("data:image/png;base64")) {
            return "png";
        } else if (imgByte.contains("data:image/jpeg;base64")) {
            return "jpeg";
        } else {
            return null;
        }
    }

    private String getFileNameNew() {
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    }

}
